import Vue from 'vue'
import VueRouter from 'vue-router'
import LayOut from '_views/LayOut'
import store from '../store'
import { isLogin } from '_utils/token'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'LayOut',
    component: LayOut,
    children: [
      {
        path: '/',
        redirect: '/dashBoard'
      },
      {
        path: '/dashBoard',
        roles: ['*'],
        name: '仪表盘',
        component: () => import('_views/DashBoard')
      },
      {
        path: '/cateLists',
        roles: ['a', 'b', 'c'],
        name: '商品分类列表',
        component: () => import('_views/CateLists')
      },
      {
        path: '/itemLists',
        name: '商品列表',
        roles: ['a', 'b', 'c'],
        component: () => import('_views/ItemLists')
      },
      {
        path: '/itemAdd',
        name: '增加商品',
        roles: ['a', 'b', 'c'],
        component: () => import('_views/ItemAdd')
      },
      {
        path: '/itemUpdate',
        name: '更新商品',
        roles: ['a', 'b', 'c'],
        component: () => import('_views/ItemUpdate')
      },
      {
        path: '/userInfo',
        name: '个人中心',
        roles: ['a', 'b', 'c'],
        component: () => import('_views/UserInfo')
      },
      {
        path: '/webSetting',
        name: '设置',
        roles: ['b', 'c'],
        component: () => import('_views/WebSetting')
      }
    ]
  },
  {
    path: '/login',
    name: '登录页',
    component: () => import('_views/Login')
  },
  {
    path: '*',
    component: () => import('_views/NotFound')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
// 登录鉴权

router.beforeEach((to, from, next) => {
  /*
    拦截 admin就可以 判断是否
  */
  if (to.path !== '/login') {
    // 判断是否登陆
    if (isLogin()) {
      // 登陆了
      next()
    } else {
      // 去登录页
      next('/login')
    }
  } else {
    next()
  }
})

// 全局后置守卫 动态添加 navTab
router.afterEach((to, from) => {
  const current = {
    name: to.name,
    path: to.path
  }
  // 如果是登录页 Layout组件 以及 dashBoard都不触发
  // 动态添加 navTab
  const noPaths = ['/login', '/dashBoard', '/']
  if (!noPaths.includes(to.path)) {
    store.commit('nav/ADD_TAB', current)
  }
})
export default router
